#!/usr/bin/python
# -*- coding:UTF-8 -*-
# @Time    : 2019/1/9 13:14
# @Author  : 王志鹏
# @Site    : 
# @File    : d1.py
# @Software: PyCharm

"""
职责链模式 (Chain of Responsibility): 使多个对象有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系.将这个对象连成一条链,
并沿着这条链传递该请求,直到有一个对象处理他为止.

好处 当一个客户提交一个请求时,请求沿着链传递直至有一个ConcreteHandler 对象负责处理它
接受者和发送者都没有对方的明确信息,且链中的对象自己也不知道链的结构,
结果是职责链可简化对象的互相链接,他们仅需保持一个指向其后继者的引用,而不需要保持他所有的时候选选择接受者
可以随时增加或修改一个请求的结构,增强了对象指派对象的灵活性
注意: 一个球球可能到了链的末端都得不到处理,或者是因为没有正确的配置而得不到处理!
"""
import abc


class Handler(object):
    __metaclass__ = abc.ABCMeta

    def __init__(self):
        self.successor = None  # type = Handler

    # 设置继任者
    def setSuccessor(self, successor):
        self.successor = successor

    @abc.abstractmethod
    def handlderRequest(self, request): pass


class ConcreteHandler1(Handler):
    def handlderRequest(self, request):
        if 0 <= request < 10:
            print "1 处理请求 %s" % (request)
        elif self.successor != None:
            self.successor.handlderRequest(request)


class ConcreteHandler2(Handler):
    def handlderRequest(self, request):
        if 10 <= request < 20:
            print "2 处理请求 %s" % (request)
        elif self.successor != None:
            self.successor.handlderRequest(request)


class ConcreteHandler3(Handler):
    def handlderRequest(self, request):
        if 20 <= request < 30:
            print "3 处理请求 %s" % (request)
        elif self.successor != None:
            self.successor.handlderRequest(request)


if __name__ == '__main__':
    h1 = ConcreteHandler1()
    h2 = ConcreteHandler2()
    h3 = ConcreteHandler3()

    h1.setSuccessor(h2)
    h2.setSuccessor(h3)
    request = [5, 12, 25, 12, 7, 6, 10, 29]
    for i, v in enumerate(request):
        h1.handlderRequest(v)
